<?php
/**
 * @author Feng
 * @date 2012-5-28
 */
class controller_admin_picture_special extends system_user_controller_special {
			
	public function action_index() {
		$this->render();
	}
	
	public function action_regroup() {
		$this->_crumbs()->addPage(system_nav_page::create($this->language('Recommend Group'))->setRoute('picture/special/regroup'));
		$concept = new picture_special_regroup_concept($this->user->getLang());
		$o = $this->_param('o');
		if(!($o = $this->_param('o'))) {
			$this->_batchDelete($concept, 'id', 'id');
			$this->view->list = $concept->fetchAll();
		} else {
			$id = intval($this->_param('id'));
			if(!($row = $concept->fetch(array('id = ?' => $id)))) {
				$row = $concept->create();
				$page = system_nav_page::create($this->language('New Group'))->setRoute('picture/special/regroup')->setParams(array('o' => 'addnew'));
			} else {
				$page = system_nav_page::create($row->getDescription())->setRoute('picture/special/regroup')->setParams(array('o' => 'edit', 'id' => $id));
			}
			$this->_crumbs()->addPage($page);
			if($this->getRequest()->isPost()) {
				$this->referer = $this->_post('referer');
				$row->setName(trim($this->_post('name')));
				$row->setDescription(trim($this->_post('description')));
				$this->_saveToDatabase($row, 'cover', 'image');
			}
			$this->view->referer = $this->referer;
			$this->view->group = $row;
		}
		$this->render();
	}
	
	public function action_addnew() {
		$row = $this->concept->create();
		$row->setIsActive(1);
		$row->setDisplayOrder(0);
		if(1 && $category_id = intval($this->_get('category_id'))) {
			$this->view->categoryList = array($category_id);
		}
		$row = $this->_saveRow($row);
		$this->view->row = $row;
		$this->view->referer = $this->referer;
		$this->_crumbs()->addPage(system_nav_page::create($this->language('New Special'))->setRoute('picture/special/addnew'));
		$this->render('picture/special/row.phtml');
	}
	
	public function action_edit() {
		$id = intval($this->_param('id'));
		if(!($row = $this->concept->fetch(array('special.id = ?' => $id)))) {
			throw new picture_exception("The Special is not Existing.");
		}
		$categoryList = array();
		$concept = new picture_special_category_concept($this->user->getLang());
		foreach($concept->fetchAll(array('special_id = ?' => $id)) AS $_row) {
			$categoryList[] = $_row->getCategoryId();
		}
		$this->view->categoryList = $categoryList;
		$row = $this->_saveRow($row);
		$this->view->row = $row;
		$this->view->referer = $this->referer;
		$this->_crumbs()->addPage(system_nav_page::create($row->getLocale()->getTitle())->setRoute('picture/special/edit')->setParams(array('id' => $row->getId())));
		$this->render('picture/special/row.phtml');
	}
	
	public function action_delete() {
		$id = intval($this->_param('id'));
		if(!($row = $this->concept->fetch(array('special.id = ?' => $id)))) {
			throw new picture_exception("The Special is not Existing.");
		}
		$categories = array();
		$sql = "";
		$sql .= "SELECT a.`special_id`, b.`category_id`, b.`title` FROM `picture_category_locale` AS b ";
		$sql .= "INNER JOIN `picture_special_category` AS a ON a.`category_id` = b.`category_id` ";
		$sql .= "WHERE a.`special_id` = '$id' AND b.`lang` = '{$this->user->getLang()}'";
		foreach(system_db::getAdapter()->fetchAll($sql) AS $category) {
			$categories[] = $category;
		}
		$localeList = array();
		$concept = new picture_special_locale_concept();
		foreach($concept->fetchAll(array('special_id = ?' => $id)) AS $locale) {
			$localeList[$locale->getLang()] = $locale;
		}
		if($this->getRequest()->isPost()) {
			$this->referer = $this->_post('referer');
			try {
				system_db::getAdapter()->beginTransaction();
				$this->_auth();
				$row->delete($this->_post('options'));
				system_db::getAdapter()->commit();
				$this->view->throwMessage = 'Complete';
			} catch (Exception $e) {
				system_db::getAdapter()->rollBack();
				$this->view->throwException = $e;
			}
		}
		$this->view->localeList = $localeList;
		$this->view->categories = $categories;
		$this->view->referer = $this->referer;
		$this->view->row = $row;
		$this->_crumbs()->addPage(system_nav_page::create($row->getLocale()->getTitle())->setRoute('picture/special/edit')->setParams(array('id' => $row->getId())));
		$this->_crumbs()->addPage(system_nav_page::create("Delete")->setRoute('picture/special/delete')->setParams(array('id' => $row->getId())));
		$this->render();
	}
	
	public function action_list() {
		$this->_crumbs()->addPage(system_nav_page::create($this->language('List'))->setRoute('picture/special/list'));
		$render = null;
		$checkedList = array();
		if($this->getRequest()->isPost() && $this->_post('addTo')) {
			$categoryList = array();
			$checkedList =  (array) $this->_post('id');
			$this->_crumbs()->addPage(system_nav_page::create($this->language('Add Special To Category'))->setRoute('picture/special/list'));
			try {
				system_db::getAdapter()->beginTransaction();
				if(empty($checkedList)) {
					throw new picture_exception("No Special selected.");
				}
				$concept = new picture_special_concept($this->user->getLang());
				$_id = implode(',', $checkedList);
				$this->view->specials = $concept->fetchAll(array("special.id IN($_id)"));
				
				$render = 'picture/special/addToCategory.phtml';
				if($this->_post('addToCategory')) {
					$categoryList =  (array) $this->_post('category');
					if(empty($categoryList)) {
						throw new picture_exception("No Category selected.");
					}
					$sql = "REPLACE INTO `picture_special_category`(`lang`, `special_id`, `category_id`) VALUES";
					$_sql = array();
					foreach($checkedList AS $id) {
						foreach($categoryList AS $cid) {
							$_sql[] = "('{$this->user->getLang()}', '$id', '$cid')";
						}
					}
					$sql .= implode(',', $_sql);
					system_db::getAdapter()->query($sql);
						
					$_id = implode(',', $categoryList);
					$sql = "UPDATE `picture_category_locale` AS `a` SET `stotal` = (
								SELECT COUNT(1) FROM `picture_special_category` WHERE `category_id` = a.`category_id` AND `lang` = '{$this->user->getLang()}'
							) WHERE a.`category_id` IN($_id)";
					system_db::getAdapter()->query($sql);
					system_db::getAdapter()->commit();
					$this->view->throwMessage = 'Complete';
				}
			} catch (Exception $e) {
				system_db::getAdapter()->rollBack();
				$this->view->throwException = $e;
			}
			$this->view->categoryList = $categoryList;
		}
		if($this->getRequest()->isPost() && $this->_post('recommend')) {
			$checkedList = (array) $this->_post('id');
			$group_id = intval($this->_post('group_id')); // 位置
			try {
				system_db::getAdapter()->beginTransaction();
				$pConcept = new picture_special_regroup_concept($this->user->getLang());
				if(!($gRow = $pConcept->fetch(array('id = ?' => $group_id)))) {
					throw new picture_exception("Unknown Group.");
				}
				$group_id = $gRow->getId();
				if(empty($checkedList)) {
					throw new picture_exception("No Item selected.");
				}
				$_id = implode(',', $checkedList);
				system_db::getAdapter()->query("DELETE FROM `picture_special_recommend` WHERE `special_id` IN($_id) AND `group_id` = '$group_id'");
				system_db::getAdapter()->query("INSERT INTO `picture_special_recommend`(`group_id`, `special_id`, `display_order`) SELECT '$group_id', `id`, `display_order` FROM `picture_special` WHERE `id` IN($_id)");
				system_db::getAdapter()->commit();
				$this->view->throwMessage = 'Complete';
			} catch (Exception $e) {
				system_db::getAdapter()->rollBack();
				$this->view->throwException = $e;
			}
		}
		$this->_saveChanges();
		if($render === null) {
			$this->_specialList("picture_special_concept");
		}
		$this->view->checkedList = $checkedList;
		$this->render($render);
	}

	public function action_recommend() {
		$this->_crumbs()->addPage(system_nav_page::create($this->language('Recommend'))->setRoute('picture/special/recommend'));
		$this->_batchDelete(new picture_special_recommend_concept($this->user->getLang()), 'id', 'recommend.special_id');
		$this->_saveChanges();
		$this->_specialList("picture_special_recommend_concept", "special.id IN(SELECT `special_id` FROM `picture_special_recommend`)");
		$this->render();
	}

	public function action_addPhoto() {
		$id = intval($this->_param('id'));
		if(!($row = $this->concept->fetch(array('special.id = ?' => $id)))) {
			throw new picture_exception("The Special is not Existing.");
		}
		$photo_id = $photoList = array();
		$this->view->row = $row;
		
		if($this->getRequest()->isPost()) {
			$photo_id = (array) $this->_post('photo_id');
			$this->referer = $this->_post('referer');
			try {
				system_db::getAdapter()->beginTransaction();
				if(empty($photo_id)) {
					throw new picture_exception("No Photo selected.");
				}
				$concept = new picture_photo_concept($this->user->getLang());
				$_id = implode(',', $photo_id);
				$photoList = $concept->fetchAll(array("photo.id IN($_id)"));
				
				$sql = "REPLACE INTO `picture_special_photo`(`special_id`, `photo_id`) VALUES";
				$_sql = array();
				foreach($photo_id AS $pid) {
					$_sql[] = "('$id', '$pid')";
				}
				$sql .= implode(',', $_sql);
				system_db::getAdapter()->query($sql);
				system_db::getAdapter()->commit();				
				$this->view->throwMessage = 'Complete';				
			} catch (Exception $e) {
				system_db::getAdapter()->rollBack();
				$this->view->throwException = $e;
			}
		}
		
		$this->view->photoList = $photoList;
		$this->view->referer = $this->referer;
		$this->_crumbs()->addPage(system_nav_page::create($row->getLocale()->getTitle())->setRoute('picture/special/edit')->setParams(array('id' => $row->getId())));
		$this->_crumbs()->addPage(system_nav_page::create($this->language('Add Photo'))->setRoute('picture/special/addPhoto')->setParams(array('id' => $row->getId())));
		$this->render();
	}
	
	public function action_photo() {
		$render = null;
		$id = intval($this->_param('id'));
		if(!($row = $this->concept->fetch(array('special.id = ?' => $id)))) {
			throw new picture_exception("The Special is not Existing.");
		}
		$this->view->row = $row;
		$this->view->special_id = $id;	
	
		$listWhere = array('photo.id IN(SELECT `photo_id` FROM `picture_special_photo` WHERE `special_id` = ?)' => $id);
		$plConcept = new picture_photo_localeConcept($this->user->getLang());
		$photo_id = array();
		if($this->getRequest()->isPost()) {
			//$this->referer = $this->_post('referer');
			try {
				if(($this->_post('batch') || $this->_post('delete')) && !$this->_post('next')) {
					$photo_id = (array) $this->_post('photo_id');
					if(empty($photo_id)) {
						throw new picture_exception("No item Selected.");
					}
					$_pid = implode(', ', $photo_id);
				}
				if($this->_post('delete')) {
					$this->_auth();
					$model = new picture_special_photo_model();
					$model->delete(array("special_id = ?" => $id, "photo_id IN($_pid)"));
					$row->updatePhotoCount();
					$this->view->throwMessage = 'Complete';
				}
				if($this->_post('batch')) {
					if(!$this->_post('next')) {
						$listWhere["photo.id IN($_pid)"] = null;
					}
					$concept = new picture_special_concept($this->user->getLang());
					$this->view->specialList = $concept->fetchAll(array("special.id = ?" => $id));
					$this->view->step = 0;
					$render = 'picture/special/photoBatchEdit.phtml';
					if($this->_post('next')) {
						foreach((array) $this->_post('photo') AS $id => $_photo) {
							if(!($row = $plConcept->fetch(array('id = ?' => $id)))) {
								continue;
							}
							try {
								system_db::getAdapter()->beginTransaction();
								$row->getLocale()->setTitle(trim($_photo['title']));
								$row->getLocale()->setDescription($_photo['description']);
								$row->setDisplayOrder(intval($_photo['display_order']));
								$row->setKeywords($_photo['tag']);
								$row->save(false);
								system_db::getAdapter()->commit();
							} catch (Exception $ex) {
								system_db::getAdapter()->rollBack();
							}
						}
						$this->view->throwMessage = 'Complete';
					}
				}
			} catch (Exception $e) {
				$this->view->throwException = $e;
			}
		}
		$this->view->checkedList = $photo_id;
		$list = $plConcept->fetchAll($listWhere, array('photo.display_order ASC'));
	
		$pids = $locale = $keyword = array();
		foreach($list AS $_row) {
			$pids[$_row->getId()] = $_row->getId();
		}
		if(!empty($pids)) {
			$pid = implode(', ', $pids);
			$concept = new picture_photo_locale_concept();
			foreach($concept->fetchAll(array("photo_id IN($pid)", 'lang = ?' => $this->user->getLang())) AS $_row) {
				$locale[$_row->getPhotoId()] = $_row;
			}
			$_kw = array();
			$concept = new resource_keyword_concept($this->user->getLang());
			foreach($concept->fetchAll(array("id IN (SELECT `keyword_id` FROM `picture_photo_keyword` WHERE `photo_id` IN($pid))")) AS $_row) {
				$_kw[$_row->getId()] = $_row->getName();
			}
			if(!empty($_kw)) {
				$pid = implode(', ', array_keys($_kw));
				$concept = new picture_photo_keyword_concept();
				foreach($concept->fetchAll(array("keyword_id IN($pid)")) AS $_row) {
					if(!isset($_kw[$_row->getKeywordId()])) continue;
					$keyword[$_row->getPhotoId()][] = $_kw[$_row->getKeywordId()];
				}
			}
		}
		$this->view->locale = $locale;
		$this->view->keyword = $keyword;
		$this->view->list = $list;
		$this->_crumbs()->addPage(system_nav_page::create($row->getLocale()->getTitle())->setRoute('picture/special/edit')->setParams(array('id' => $row->getId())));
		$this->_crumbs()->addPage(system_nav_page::create($this->language('Photo List'))->setRoute('picture/special/photo')->setParams(array('id' => $row->getId())));
		$this->render($render);
	}
	
}
